package com.runen.infinitemovement.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.runen.infinitemovement.Constant;
import com.runen.infinitemovement.R;
import com.runen.infinitemovement.adapter.CommentDetailsAdapter;
import com.runen.infinitemovement.adapter.HeardPictureAdapter;
import com.runen.infinitemovement.base.BaseActivity;
import com.runen.infinitemovement.model.api.ActivityAPI;
import com.runen.infinitemovement.model.base.BaseResponseEntity;
import com.runen.infinitemovement.model.entity.CollageDetailsEntity;
import com.runen.infinitemovement.model.entity.CommentDetailListBean;
import com.runen.infinitemovement.model.entity.ReplyCommentListBean;
import com.runen.infinitemovement.tool.CommonUtil;
import com.runen.infinitemovement.tool.GlideUtils;
import com.runen.infinitemovement.tool.KeyboardStateObserver;
import com.runen.infinitemovement.widget.goodview.GoodView;
import com.runen.infinitemovement.widget.imageview.RoundedCornersImage;
import com.runen.infinitemovement.widget.popupwind.SharePoppupWindow;
import com.runen.rxnetlibrary.net.callback.BaseResultCallback;
import com.runen.rxnetlibrary.utils.LogUtil;
import com.runen.rxnetlibrary.utils.TimeUtil;
import com.runen.rxnetlibrary.utils.ToastUtils;

import org.json.JSONException;
import org.json.JSONObject;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class ColumnDetailsActivity extends BaseActivity implements SwipeRefreshLayout.OnRefreshListener {

    @BindView(R.id.top_btn_left)
    Button topBtnLeft;
    @BindView(R.id.tv_comment_sum)
    TextView tvCommentSum;
    @BindView(R.id.rv_column_comment)
    RecyclerView rvColumnComment;
    @BindView(R.id.tv_column_name)
    TextView tvColumnName;
    @BindView(R.id.ric_column_header)
    RoundedCornersImage ricColumnHeader;
    @BindView(R.id.tv_company_type)
    TextView tvCompanyType;
    @BindView(R.id.tv_date)
    TextView tvDate;
    @BindView(R.id.column_web)
    WebView columnWeb;
    @BindView(R.id.top_title)
    TextView topTitle;
    @BindView(R.id.top_btn_right)
    Button topBtnRight;
    @BindView(R.id.top_tv_right)
    TextView topTvRight;
    @BindView(R.id.top_iv_right)
    ImageView topIvRight;
    @BindView(R.id.v_title_line)
    View vTitleLine;
    @BindView(R.id.ll_title)
    LinearLayout llTitle;
    @BindView(R.id.rv_liked_picture_list)
    RecyclerView rvLikedPictureList;
    @BindView(R.id.tv_liked_sum)
    TextView tvLikedSum;
    @BindView(R.id.ll_liked)
    LinearLayout llLiked;
    @BindView(R.id.srl)
    SwipeRefreshLayout srl;
    @BindView(R.id.edt_input_message)
    EditText edtInputMessage;
    @BindView(R.id.rl_like)
    RelativeLayout rl_like;
    @BindView(R.id.iv_praise)
    ImageView ivPraise;
    @BindView(R.id.tv_praise_sum)
    TextView tvPraiseSum;
    @BindView(R.id.tv_null_comment)
    TextView tv_null_comment;
    private CommentDetailsAdapter commentDetailsAdapter;
    private String informationId;
    private HeardPictureAdapter heardPictureAdapter;
    private CommentDetailListBean commentDetailListBean;
    private ReplyCommentListBean replyCommentListBean;
    private String topItemCommentId;
    private String replyUserId;
    private int level = 0;//0为一级评论，1为二级评论

    @Override
    protected int getLayoutId() {
        return R.layout.activity_columndetails;
    }

    @Override
    protected void initView(@Nullable Bundle savedInstanceState) {
        ButterKnife.bind(this);
        informationId = getIntent().getStringExtra("informationId");
        LogUtil.e("informationId", informationId + "");
        vTitleLine.setVisibility(View.GONE);
        /**
         * 评论
         */
        srl.setOnRefreshListener(this);
        LinearLayoutManager commentLayoutManager = new LinearLayoutManager(this);
        commentLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        rvColumnComment.setLayoutManager(commentLayoutManager);
        commentDetailsAdapter = new CommentDetailsAdapter(this);
        rvColumnComment.setAdapter(commentDetailsAdapter);

        LinearLayoutManager layoutManager4 = new LinearLayoutManager(this);
        layoutManager4.setOrientation(RecyclerView.HORIZONTAL);
        rvLikedPictureList.setLayoutManager(layoutManager4);
        heardPictureAdapter = new HeardPictureAdapter(this);
        rvLikedPictureList.setAdapter(heardPictureAdapter);

        KeyboardStateObserver.getKeyboardStateObserver(this).
                setKeyboardVisibilityListener(new KeyboardStateObserver.OnKeyboardVisibilityListener() {
                    @Override
                    public void onKeyboardShow() {
//                        Toast.makeText(ColumnDetailsActivity.this,"键盘弹出",Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onKeyboardHide() {
                        //键盘关闭
                        edtInputMessage.setText("");
                        edtInputMessage.setHint("说点什么吧...");
                        commentDetailListBean = null;
                        replyCommentListBean = null;
                        level = 0;
                    }
                });

        initData();

        commentDetailsAdapter.setOnItemCommentClick(new CommentDetailsAdapter.OnItemCommentClick() {
            @Override
            public void onItemPraise(CommentDetailListBean item) {
                sendOrCancelPrise(item);
            }

            @Override
            public void onItemCommentReply(CommentDetailListBean item, String topCommentId) {
                //评论回复
                commentDetailListBean = item;
                replyUserId = item.reviewerId;
                topItemCommentId = topCommentId;
                level = 1;
                edtInputMessage.setHint("回复" + item.nickname + "：");
                CommonUtil.showKeyboard(edtInputMessage);
            }

            @Override
            public void onItemSecondReply(ReplyCommentListBean item, String topCommentId) {
                replyCommentListBean = item;
                topItemCommentId = topCommentId;
                replyUserId = item.reviewerId;
                level = 1;
                edtInputMessage.setHint("回复" + item.reviewerName + "：");
                CommonUtil.showKeyboard(edtInputMessage);
            }

            @Override
            public void onItemMore(CommentDetailListBean item, String topCommentId) {
                Intent intent = new Intent(ColumnDetailsActivity.this, SecondReplyCommentActivity.class);
                intent.putExtra("commentId", item.commentId);
                intent.putExtra("targetId", dataBean.informationId);
                startActivity(intent);
            }
        });

        edtInputMessage.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEND) {//修改回车键功能
                    //代码
                    String edtString = v.getText().toString().trim();
                    Log.e("TAG", "onEditorAction: " + topItemCommentId);
                    if (TextUtils.isEmpty(edtString)) {
                        ToastUtils.showShort("请输入评论信息！！！");
                    } else {
                        onComment(edtString, commentDetailListBean, replyCommentListBean);
                    }
                }
                return false;
            }
        });
    }

    private CollageDetailsEntity.DataBean dataBean;

    private void initData() {
        srl.setRefreshing(true);
        String string = "?informationId=%s";
        new ActivityAPI().getCollageDetails(String.format(string, informationId), new BaseResultCallback<CollageDetailsEntity>() {
            @Override
            public void onResponse(CollageDetailsEntity response) {
                srl.setRefreshing(false);
                if (response.code == 0) {
                    if (response.data != null) {
                        dataBean = response.data;
                        tvColumnName.setText(response.data.title);
                        String str = "（%s）";
                        if (response.data.commentNumber == 0) {
                            tv_null_comment.setVisibility(View.VISIBLE);
                            rvColumnComment.setVisibility(View.GONE);
                        } else {
                            tv_null_comment.setVisibility(View.GONE);
                            rvColumnComment.setVisibility(View.VISIBLE);
                        }
                        tvCommentSum.setText(String.format(str, response.data.commentNumber));
                        if (TextUtils.isEmpty(response.data.publishTime)) {
                            tvDate.setText("0");
                        } else {
                            tvDate.setText(TimeUtil.dealDateFormat(response.data.publishTime));
                        }

                        CommonUtil.loadData(response.data.content, columnWeb);
                        if (response.data.likeHeadImages != null && response.data.likeHeadImages.size() > 0) {
                            heardPictureAdapter.setNewData(response.data.likeHeadImages);
                        }
                        String likeNum = "%s 人赞过";
                        tvLikedSum.setText(String.format(likeNum, response.data.likeNumber));
                        tvPraiseSum.setText(String.valueOf(dataBean.likeNumber));
                        if (dataBean.isLike) {
                            GlideUtils.loadImage(getApplicationContext(), CommonUtil.getDrawable(R.mipmap.ico_praised), ivPraise);
                        } else {
                            GlideUtils.loadImage(getApplicationContext(), CommonUtil.getDrawable(R.mipmap.ico_like), ivPraise);
                        }

                        if (response.data.commentsPageDto != null && response.data.commentsPageDto.size() > 0) {
                            commentDetailsAdapter.setNewData(response.data.commentsPageDto);
                        }
                    }
                } else {
                    ToastUtils.showShort(response.msg);
                }
            }
        });
    }

    @OnClick({R.id.top_btn_left, R.id.ll_liked, R.id.rl_like, R.id.iv__share})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.top_btn_left:
                finish();
                break;
            case R.id.ll_liked:
                Intent intent = new Intent(this, ReceiveLikedActivity.class);
                intent.putExtra("dynamicId", informationId);
                intent.putExtra("dynamicFlag", 1);
                startActivity(intent);
                break;
            case R.id.rl_like:
                if (null != dataBean) {
                    if (dataBean.isLike) {
                        dataBean.likeNumber = dataBean.likeNumber - 1;
                        dataBean.isLike = false;
                        GlideUtils.loadImage(getApplicationContext(), CommonUtil.getDrawable(R.mipmap.ico_like), ivPraise);
                    } else {
                        dataBean.likeNumber = dataBean.likeNumber + 1;
                        dataBean.isLike = true;
                        GoodView goodView = new GoodView(this);
                        goodView.setImage(R.mipmap.ico_praised);
                        goodView.show(ivPraise);
                        GlideUtils.loadImage(getApplicationContext(), CommonUtil.getDrawable(R.mipmap.ico_praised), ivPraise);
                    }
                    String likeNum = "%s 人赞过";
                    tvLikedSum.setText(String.format(likeNum, dataBean.likeNumber));
                    tvPraiseSum.setText(String.valueOf(dataBean.likeNumber));
                    onPraise(dataBean);
                }
                break;
            case R.id.iv__share:
                if (dataBean != null) {
                    SharePoppupWindow sharePoppupWindow = SharePoppupWindow.getInstance(this, dataBean.title,
                            "", String.format(Constant.NEWS_DETAILS_SHARE, informationId));
                    sharePoppupWindow.show();
                }

                break;
        }
    }

    private void onPraise(CollageDetailsEntity.DataBean dataBean) {
        JSONObject object = new JSONObject();
        try {
            object.put("likeDataId", dataBean.informationId);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        new ActivityAPI().zxCommentLikeAndCancel(dataBean.isLike, object.toString(), new BaseResultCallback<BaseResponseEntity<?>>() {
            @Override
            public void onResponse(BaseResponseEntity<?> response) {
//                ToastUtils.showShort(response.getMessage());
            }

            @Override
            public void onComplete() {
                super.onComplete();

            }
        });

    }

    /**
     * 评论点赞
     *
     * @param CommentDetailListBean
     * @param
     */
    private void sendOrCancelPrise(CommentDetailListBean CommentDetailListBean) {
        JSONObject object = new JSONObject();
        try {
            object.put("toLikeUserId", CommentDetailListBean.reviewerId);
            object.put("likeDataId", CommentDetailListBean.commentId);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        new ActivityAPI().commentLikeAndCancel(CommentDetailListBean.isLike, object.toString(), new BaseResultCallback<BaseResponseEntity<?>>() {
            @Override
            public void onResponse(BaseResponseEntity<?> response) {
//                ToastUtils.showShort(response.getMessage());
            }

            @Override
            public void onComplete() {
                super.onComplete();

            }
        });
    }

    /**
     * 对文章的评论
     *
     * @param edtString
     */
    private void onComment(String edtString, final CommentDetailListBean commentDetailList, final ReplyCommentListBean replyCommentList) {
        JSONObject object = new JSONObject();
        try {
            object.put("commentType", "0");
            object.put("content", edtString);
            object.put("targetId", informationId);
            object.put("replyUserId", level == 0 ? informationId : replyUserId);
            if (null != commentDetailList) {
                object.put("replyId", commentDetailList.commentId);
                object.put("replyUserId", commentDetailList.reviewerId);
                object.put("topCommentId", topItemCommentId);
            } else if (null != replyCommentList) {
                object.put("replyArticleCommentsId", replyCommentList.commentId);
                object.put("replyUserId", replyCommentList.reviewerId);
                object.put("topCommentId", topItemCommentId);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        new ActivityAPI().onDynamicComment(object.toString(), new BaseResultCallback<BaseResponseEntity<?>>() {
            @Override
            public void onResponse(BaseResponseEntity<?> response) {

            }

            @Override
            public void onComplete() {
                super.onComplete();
                CommonUtil.hideKeyboard(ColumnDetailsActivity.this);
                edtInputMessage.setText("");
                edtInputMessage.setHint("说点什么吧...");
                commentDetailListBean = null;
                replyCommentListBean = null;
                level = 0;
                onRefresh();
            }
        });
    }


    @Override
    public void onRefresh() {
        initData();
    }
}
